<template>
  <base-breadcrumb>
    <a-row :gutter="10" class="page-height">
      <!-- 树搜索 -->
      <a-col :span="6">
        <a-card class="page-height-tree">
          <title-name title="公司组织架构" />
          <!-- 公司组织树搜索 -->
          <tree-organization
            ref="treeOrganization"
            :expand-by-auto="true"
            :auto-select="false"
            :contain-virtual="true"
            :org-query="{ baseOrgType: 0, containVirtual: 1 }"
            :selected-keys.sync="selectedKeys"
            :select-options.sync="selectOptions"
            :show-child-with-search="true"
            @loader="getTable"
            @searchEmpty="handleSearchEmpty"
          />
        </a-card>
      </a-col>
      <a-col :span="18"  class="page-height-list-wrapper">
        <searchData
          :search-data="searchArr"
          @search="useSearch"
        />
        <a-card class="mb20 page-height-list">
          <!-- <div class="pub-table-action-btn">
            
          </div> -->
          <a-spin
            tip="加载中..."
            :spinning="flowRequesting"
          >
          <list-table
            ref="table"
            row-key="id"
            :columns="columns"
            :request="loadData"
            :pageKeys="['pageNo', 'pageSize', 'total']"
            :alert="true"
          >
            <a-button
              slot="prefix"
              v-btnPermission="'sy_003_add_01'"
              icon="plus"
              class="btn_right"
              type="primary"
              @click="handleUpdate('add')"
            >
              新增用户信息
            </a-button>
            <template
              slot="postPNames"
              slot-scope="text"
            >
              <div
                class="ellipsis"
                :title="filterPostPName(text)"
              >
                {{ filterPostPName(text) }}
              </div>
            </template>
            <template
              slot="accountType"
              slot-scope="text, record"
            >
              <span v-if="record.accountType == 1">永久账号</span>
              <span v-if="record.accountType == 0">临时账号</span>
            </template>
            <template
              slot="operation"
              slot-scope="text, record"
            >
              <MoreButton class="pub-table-list-action">
                <a
                  v-btnPermission="'sy_003_loo_02'"
                  @click="handleUpdate('look', record)"
                >查看</a>
                <a
                  v-btnPermission="'sy_003_edi_03'"
                  @click="handleUpdate('edit', record)"
                >编辑</a>
                <a
                  v-btnPermission="'sy_003_bin_04'"
                  @click="handleBind(record)"
                >绑定岗位</a>
                <a
                  v-btnPermission="'sy_003_del_06'"
                  @click="handleUpdate('delete', record)"
                >删除</a>
              </MoreButton>
            </template>
          </list-table>
          </a-spin>
        </a-card>
      </a-col>
    </a-row>
    <modalPsw
      :visible="psw.visible"
      @handleCancel="handleCancelPsw"
    />
    <modalBindOrg
      :form="bindOrgForm"
      :visible-job="bindOrg.visible"
      @handleCancel="handleCancelBindOrg"
      @confirm="handleConfirmBind"
    />
    <modalUpdateStatus
      :id="currentId"
      :visible="updateStatus.visible"
      @handleCancel="handleCancelUpdateStatus"
    />
  </base-breadcrumb>
</template> 

<script>
import TreeOrganization from '@/components/businessComponents/TreeOrganization' // 树
import modalPsw from './modalPsw' // 重置密码
import modalBindOrg from './modalBindOrg' // 绑定组织
import modalUpdateStatus from './modalUpdateStatus' // 更新状态
import { searchArr, columns } from './model'
import { getOneOrgUsers, deleteEmployeeByUserId } from '@/api/commons.js'
import { packageConfirm } from '@/utils/baseAction.js'

export default {
  name: 'UserManage',
  components: {
    TreeOrganization,
    modalPsw,
    modalBindOrg,
    modalUpdateStatus,
  },
  data() {
    return {
      //密码重置
      psw: {
        visible: false,
      },
      bindOrg: {
        visible: false,
      },
      updateStatus: {
        visible: false,
      },
      flowRequesting: false,
      bindOrgForm: {},
      searchArr: searchArr,
      columns: columns,
      chooseData: 0,
      tableData: [],
      selectedRowKeys: [],
      selectedRows: [],
      selectedKeys: [], // 选中节点
      selectOptions: {}, // 选中节点对象

      orgId: '',
      currentId: '', //当前选中人员ID
      pagination: {
        defaultCurrent: 1, // 默认当前页数
        current: 1,
        defaultPageSize: 10, // 默认当前页显示数据的大小
        total: 0, // 总数，必须先有
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ['5', '10', '15', '20'],
        showTotal: (total) => `共 ${total} 条`, // 显示总数
        onShowSizeChange: (current, pageSize) => {
          this.pagination.current = 1
          this.pagination.defaultPageSize = pageSize
          this.getTable() //显示列表的接口名称
        },
        // 改变每页数量时更新显示
        onChange: (current, size) => {
          this.pagination.current = current
          this.pagination.defaultPageSize = size
          this.getTable()
        },
      },
      pathName: this.$route.path,

      isTableList: false,
      cacheSearch: {},  // 搜索参数
      loadData: (parameter) => {
        if (!this.isTableList) return false;

        let searchData = Object.assign(
          {
            pageNumber: parameter.pageNo,
            pageSize: parameter.pageSize,
            queryPostRelation: true,
            rootOrgId: this.selectedKeys[0] || '',
            types: [0], // 公司内部用户
          },
          this.cacheSearch
        )

        return getOneOrgUsers(searchData).then((res) => {
          return { code: 200, data: res.data, total: res.data?.total }
        })
      }, // 加载数据方法 必须为 Promise 对象
    }
  },
  computed: {
    containTags(){
      return this.$store.getters['GET_ORGLABEL'].map(item => item.code)
    }
  },
  mounted() {
    this.$refs.treeOrganization.getList().then((res) => {
      this.getTable()
    })
    console.log('mounted-----------table的Path', this.pathName)
    // 监听详情页返回刷新列表
    //this.pathName取的值是this.$route.path
    this.$bus.$on('handleRefresh' + this.pathName, () => {
      console.log('--------------------收到了，刷新刷新刷新----------------',this.pathName)
      this.getTable()
    })
  },
  beforeDestroy() {
    console.log('beforeDestroy-------table的Path', this.pathName)
    this.$bus.$off('handleRefresh' + this.pathName)
  },
  methods: {
    useSearch(val) {
      console.log(val)
      this.pagination.current = 1 // 重置页码
      this.handleSearch(val)
    },
    handleSearchEmpty() {
      this.selectedKeys = []
      this.selectOptions = {}
    },
    /**
     * 处理数据增删改查等操作
     */
    handleUpdate(type, data = {}) {
      const commonHanlder = (data) => {
        this.$router.push({
          path: '/systemManage/userManage/updateUser',
          query: {
            pageType: type,
            id: data.id || '',
            userId: data.userId || ''
          }
        })
      }
      const actionMap = {
        'add': commonHanlder,
        'edit': commonHanlder,
        'look': commonHanlder,
        'delete': this.handleDelete
      }
      actionMap[type] && actionMap[type](data)
    },
    filterPostPName(val) {
      if (val === null) return ''
      return (
        val.reduce &&
        val.reduce((pre, cur) => {
          return pre === '' ? cur : pre + '、' + cur
        }, '')
      )
    },
    /**
     *@desc  获取组织列表
     *@param {}
     */
    getTable() {
      let that = this
      // setTimeout(that.handleSearch)

      this.isTableList = true;
      this.$refs.table.refresh(true)
    },
    /**
     *@desc  table表格搜索
     *@param {}
     */
    handleSearch(val) {
      this.cacheSearch = {...val} //缓存搜索参数
      // this.handleTable(this.cacheSearch)
      this.$refs.table.refresh(true)
    },
    /**
     *@desc  table表格列表
     *@param {}
     */
    handleTable(params) {
      console.log(this.selectedKeys)
      let _this = this
      let searchData = Object.assign(
        {
          pageNumber: _this.pagination.current,
          pageSize: _this.pagination.defaultPageSize,
          queryPostRelation: true,
          rootOrgId: _this.selectedKeys[0] || '',
          types: [0], // 公司内部用户
        },
        params
      )
      this.flowRequesting = true
      getOneOrgUsers(searchData).then((res) => {
        this.flowRequesting = false
        _this.pagination.total = res.data.total
        _this.tableData = []
        _this.tableData = res.data.list || []
      })
    },
    /**
     *@desc  table表格选中
     *@param {}
     */
    onSelectChange(selectedRowKeys, selectedRows) {
      let _this = this
      _this.selectId = []
      selectedRows.map((item) => {
        // 选中id
        _this.selectId.push(item.id)
      })
      this.chooseData = this.chooseData + selectedRows.length
      _this.selectedRowKeys = selectedRowKeys
      _this.selectedRows = selectedRows
    },
    /**
     *@desc  table列表删除
     *@param {}
     */
    handleDelete(record) {
      packageConfirm({
        callback: async () => {
          await deleteEmployeeByUserId({ userId: record.userId })
          this.$message.success('删除成功')
          this.handleSearch()
        }
      })
    },
    /**
     *@desc  table表格绑定组织modal
     *@param {}
     */
    handleBind(e) {
      this.psw.visible = false
      this.bindOrg.visible = true
      this.bindOrgForm = e
      this.updateStatus.visible = false
    },
    /**
     *@desc  table列表密码重置取消cancel
     *@param {}
     */
    handleCancelPsw(val) {
      this.handleSearch(this.cacheSearch)
      this.psw.visible = val
    },
    handleCancelBindOrg() {
      this.bindOrg.visible = false
    },
    /**
     * 岗位绑定确认，刷新列表
     */
    handleConfirmBind() {
      this.handleCancelBindOrg()
      this.handleSearch(this.cacheSearch)
    },
    /**
     *@desc  table列表更新状态cancel
     *@param {}
     */
    handleCancelUpdateStatus(val) {
      this.handleSearch(this.cacheSearch)
      this.updateStatus.visible = val
    },
  },
}
</script>

<style lang="less" scoped>
.ellipsis {
  max-width: 450px;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  white-space: nowrap;
}
</style>
